package com.gec.system.utils;

import com.gec.model.system.ITripUser;
import com.gec.system.service.ITripMenuService;
import com.gec.system.service.ITripUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ITripUserService iTripUserService;
    @Autowired
    private ITripMenuService iTripMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("认证账号：" + username);
        ITripUser iTripUser = iTripUserService.getUserInfoUserName(username);

        if(null == iTripUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        if(iTripUser.getActivated().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        List<String> userPermsList = iTripMenuService.findUserPermsList(iTripUser.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new UserDetailImpl(iTripUser, authorities);
    }
}
